package com.eric.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.eric.domain.po.User;
import com.eric.domain.vo.UserVO;
import com.eric.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.eric.domain.po.table.UserTableDef.USER;


@RestController
@RequiredArgsConstructor
@RequestMapping("")

@Validated
public class UserLogin {

    private final UserService userService;

    /*@PostMapping("/login")
    public SaResult doLogin(@RequestBody Map<String,String>loginObj){

        UserVO userVO = userService.queryChain().select()
                .from(User.class).
                where(USER.LOGIN_NAME.eq(loginObj.get("userName")))
                .oneAs(UserVO.class);

//        校验密码
        boolean checkPw = BCrypt.checkpw(loginObj.get("password"), userVO.getPassword());

        if (loginObj.get("userName").equals(userVO.getLoginName())&&checkPw){
//            这个id:10001有点问题
            StpUtil.login(1000+userVO.getId(),true);
            return SaResult.data(StpUtil.getTokenValue());
        }
        return SaResult.error("登录失败！");*/



    @PostMapping("/login")
    public SaResult doLogin(@Validated @RequestBody  UserVO loginObj){

        System.out.println(loginObj);
        UserVO userVO = userService.queryChain().select()
                .from(User.class).
                where(USER.LOGIN_NAME.eq(loginObj.getLoginName()))
                .oneAs(UserVO.class);

//        校验密码
        boolean checkPw = BCrypt.checkpw(loginObj.getPassword(), userVO.getPassword());
        System.out.println("============》"+checkPw);

        if (loginObj.getLoginName().equals(userVO.getLoginName())&&checkPw){
//            这个id:10001有点问题
            StpUtil.login(1000+userVO.getId(),true);
            return SaResult.data(StpUtil.getTokenValue());
        }
        return SaResult.error("登录失败！");
    }

    @GetMapping("/logOut")
    public SaResult doLogOut(){
        StpUtil.logout();
        return SaResult.ok("已经退出！");
    }
}
